package com.ahao.filter;


import com.ahao.model.User;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter(urlPatterns = "/*")
public class PermissFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        //获取请求地址
        String url = req.getRequestURI();
        if (url.contains("login") || url.contains("easyui") || url.contains("h-ui")) {
            //登录或者静态资源相关，直接放行
            filterChain.doFilter(servletRequest, servletResponse);
        }else {
            //获取session中的用户信息
            User user = (User) req.getSession().getAttribute("loginUser");
            if (user == null) {
                //没有登录，跳转到登录页面
                resp.sendRedirect(req.getContextPath()+"/login");
            }else {
                //用户已登录，放行
                filterChain.doFilter(servletRequest, servletResponse);
            }
        }
    }

    @Override
    public void destroy() {

    }
}
